# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import except_orm, Warning
from datetime import date, datetime
import os, time


class param_create_reduction_analytic(osv.osv_memory):
    _name = 'param.create.reduction.analytic'
    _description = 'create reduction adjustment analytic'
      
    _columns = {
        'int_type_id': fields.many2one('int.type', 'Sequence Type', required=True, domain=[('type','=','reduction')]),
        'inventory_date': fields.datetime('Inventory Date'),
        'ship_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Shipyard Reduction Lines',
            domain=[('type','=','shipyard')], context={'default_type':'shipyard'}),
        'mech_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Mechanical Reduction Lines',
            domain=[('type','=','mechanical')], context={'default_type':'mechanical'}),
        'elec_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Electrical Reduction Lines',
            domain=[('type','=','electrical')], context={'default_type':'electrical'}),
        'weld_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Welding & Fabrication Reduction Lines',
            domain=[('type','=','welding_fabrication')], context={'default_type':'welding_fabrication'}),
        'int_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Interior Reduction Lines',
            domain=[('type','=','interior')], context={'default_type':'interior'}),
        'desg_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Design Reduction Lines',
            domain=[('type','=','design')], context={'default_type':'design'}),
        'dept1_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Department1 Reduction Lines',
            domain=[('type','=','other_dept1')], context={'default_type':'other_dept1'}),
        'dept2_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Departmen2 Reduction Lines',
            domain=[('type','=','other_dept2')], context={'default_type':'other_dept2'}),
        'dept3_red_line_ids':fields.one2many('param.create.reduction.analytic.line','reduction_analytic_id','Department3 Reduction Lines',
            domain=[('type','=','other_dept3')], context={'default_type':'other_dept3'}),
    }
    
    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        acc_analytic_obj = self.pool.get('account.analytic.account')
        res = super(param_create_reduction_analytic, self).default_get(cr, uid, fields, context=context)
        ship_red_lines = []
        mech_red_lines = []
        elec_red_lines = []
        weld_red_lines = []
        int_red_lines  = []
        desg_red_lines = []
        dept1_red_lines = []
        dept2_red_lines = []
        dept3_red_lines = []
        
        for lines in acc_analytic_obj.browse(cr, uid, context.get(('active_ids'), []), context=context):            
            if lines.ship_state == 'approved':
                if lines.shipyard_line_ids:
                    for i in lines.shipyard_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id, 
                                'real_qty': i.real_qty, 
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            ship_red_lines.append(item)
                    res.update({'ship_red_line_ids': ship_red_lines})
            if lines.mech_state == 'approved': 
                if lines.mechanical_line_ids:
                    for i in lines.mechanical_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,  
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            mech_red_lines.append(item)
                    res.update({'mech_red_line_ids': mech_red_lines})
            if lines.elec_state == 'approved':        
                if lines.electrical_line_ids:
                    for i in lines.electrical_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,  
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            elec_red_lines.append(item)
                    res.update({'elec_red_line_ids': elec_red_lines})
            if lines.weld_state == 'approved':         
                if lines.welding_line_ids:
                    for i in lines.welding_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,  
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            weld_red_lines.append(item)
                    res.update({'weld_red_line_ids': weld_red_lines})
            if lines.int_state == 'approved':    
                if lines.interior_line_ids:
                    for i in lines.interior_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            int_red_lines.append(item)
                    res.update({'int_red_line_ids': int_red_lines})
            if lines.desg_state == 'approved':          
                if lines.design_line_ids:
                    for i in lines.design_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            desg_red_lines.append(item)
                    res.update({'desg_red_line_ids': desg_red_lines})
            if lines.dept1_state == 'approved':          
                if lines.department1_line_ids:
                    for i in lines.department1_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            dept1_red_lines.append(item)
                    res.update({'dept1_red_line_ids': dept1_red_lines})
            if lines.dept2_state == 'approved':          
                if lines.department2_line_ids:
                    for i in lines.department2_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            dept2_red_lines.append(item)
                    res.update({'dept2_red_line_ids': dept2_red_lines})
            if lines.dept3_state == 'approved':          
                if lines.department3_line_ids:
                    for i in lines.department3_line_ids:
                        if (i.process_qty - i.deducted_quantity) != 0:
                            item = {
                                'product_id': i.product_id.id,
                                'product_qty': i.process_qty - i.deducted_quantity,
                                'product_uom': i.product_uom.id,
                                'unit_price': i.unit_price,
                                'can_process_qty': i.process_qty - i.deducted_quantity,
                                'analytic_line_id': i.id,
                            }
                            dept3_red_lines.append(item)
                    res.update({'dept3_red_line_ids': dept3_red_lines})

        return res
    
    def analytic_reduction_create_line(self, cr, uid, ids, context=None):
        if context is None :
            context = {}
        
        stock_inventory_obj = self.pool.get('stock.inventory')
        stock_inventory_line_obj = self.pool.get('stock.inventory.line')
        analy_reduc_obj = self.pool.get('param.create.reduction.analytic')
        account_analy_obj = self.pool.get('account.analytic.account')
        stock_picking_type_obj = self.pool.get('stock.picking.type')
        user_obj = self.pool.get('res.users')
        
        data = self.browse(cr, uid, ids, context=context)
        stock_picking_ids = stock_picking_type_obj.search(cr, uid, [('code', '=', 'internal'),('active', '=', True)], context=context)
        id_dest_location = stock_picking_type_obj.browse(cr, uid, stock_picking_ids, context=context)[0].default_location_dest_id.id
         
        analytic_inv_lines = []
         
        user_ids = user_obj.search(cr, uid, [('id','=',uid)])
        if user_ids :
            tz = user_obj.browse(cr, uid, user_ids[0])
            tz_name = tz.tz
             
        os.environ['TZ'] = str(tz_name) #set time zone secara otomatis tidak hard code
        time.tzset() 
         
        
        if data.inventory_date : 
            date_inv = data.inventory_date 
        else : 
            d= (time.strftime("%m/%d/%Y")) +' '+ (time.strftime("%H:%M:%S")) 
            date_inv = d
        analytic_id = context.get(('active_ids'), [])
        analytic_id = analytic_id and analytic_id[0] or False
        stock_inventory_vals = {
                'analytic_account_id': analytic_id,
                'location_id': id_dest_location,
                'int_type_id': data.int_type_id.id, 
                'date' : date_inv,
                }
        stock_inv_id = stock_inventory_obj.create(cr, uid, stock_inventory_vals, context=context)
         
        for inv_reduct_line_shipyard in data.ship_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_shipyard.product_id.id, 
                    'product_uom_id': inv_reduct_line_shipyard.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_shipyard.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_shipyard.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
        
        for inv_reduct_line_mechanical in data.mech_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_mechanical.product_id.id, 
                    'product_uom_id': inv_reduct_line_mechanical.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_mechanical.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_mechanical.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
        
        for inv_reduct_line_electrical in data.elec_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_electrical.product_id.id, 
                    'product_uom_id': inv_reduct_line_electrical.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_electrical.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_electrical.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
            
        for inv_reduct_line_welding in data.weld_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_welding.product_id.id, 
                    'product_uom_id': inv_reduct_line_welding.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_welding.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_welding.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
        
        for inv_reduct_line_interior in data.int_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_interior.product_id.id, 
                    'product_uom_id': inv_reduct_line_interior.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_interior.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_interior.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
            
        for inv_reduct_line_design in data.desg_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_design.product_id.id, 
                    'product_uom_id': inv_reduct_line_design.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_design.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_design.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
        
        for inv_reduct_line_dept1 in data.dept1_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_dept1.product_id.id, 
                    'product_uom_id': inv_reduct_line_dept1.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_dept1.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_dept1.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
        
        for inv_reduct_line_dept2 in data.dept2_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_dept2.product_id.id, 
                    'product_uom_id': inv_reduct_line_dept2.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_dept2.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_dept2.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
            
        for inv_reduct_line_dept3 in data.dept3_red_line_ids:

            item = {
                    'location_id': id_dest_location,
                    'product_id': inv_reduct_line_dept3.product_id.id, 
                    'product_uom_id': inv_reduct_line_dept3.product_id.uom_id.id,
                    'product_qty': inv_reduct_line_dept3.product_qty,
                    'price_unit': 0.0,
                    'analytic_line_id': inv_reduct_line_dept3.analytic_line_id.id,
                }
            analytic_inv_lines.append(item)
            
        for stock_inv_line in analytic_inv_lines :
            stock_inv_line['inventory_id']= stock_inv_id
            stock_inventory_line_obj.create(cr, uid, stock_inv_line, context=context)
        stock_inventory_obj.action_done2(cr,uid, [stock_inv_id],context=None)
        action_model = False
        action = {} 
        
        data_pool = stock_inventory_obj.pool.get('ir.model.data')
         
        action_id = data_pool.xmlid_to_res_id(cr, uid, 'stock.action_inventory_form')

        if action_id:
            action_pool = stock_inventory_obj.pool['ir.actions.act_window']
            action = action_pool.read(cr, uid, action_id, context=context)
            action['domain'] = "[('id','in', ["+','.join(map(str,[stock_inv_id,]))+"])]"
            return action
        return True
        
        
#         return stock_inv_id
    
    def _get_analytic_reduction_vals(self, cr, uid, key,context=None):
        if context is None:
            context = {}
        location_id, int_type_id = key

        return  
     
    
class param_create_reduction_analytic_line(osv.osv_memory):
    _name = 'param.create.reduction.analytic.line'
    _description = 'Create Reduction Analytic Line'
    
    _columns = {
        'reduction_analytic_id': fields.many2one('param.create.reduction.analytic', 'Reduction Analytic Account', required=True, ondelete='cascade', select=True),
        'analytic_line_id': fields.many2one('analytic.quotation.line', 'Analytic Lines', ondelete='cascade'),
        'product_id': fields.many2one('product.product', 'Product', readonly=True),
        'product_qty': fields.float('Quantity',required=True), 
        'product_uom': fields.many2one('product.uom', 'Unit of Measure ', required=True),
        'type':fields.selection([('shipyard','Shipyard'),
                                 ('mechanical','Mechanical'),
                                 ('electrical','Electrical'),
                                 ('welding_fabrication','Welding & Fabrication'),
                                 ('interior','Interior'),
                                 ('design','Design'),
                                 ('other_dept1','Other Department1'),
                                 ('other_dept2','Other Department2'),
                                 ('other_dept3','Other Department3')
                                 ], 'Type'),  
        'can_process_qty': fields.float('Can Process Quantity', readonly=True), 
    }
    
    def onchange_process_qty(self, cr, uid, ids, product_qty, can_process_qty, context=None):
        if context is None:
            context = {}
        res={}
        
        warning = False
        warning_msgs = '' 
        
        if not product_qty:
            res['product_qty'] = can_process_qty
            warning_msgs = 'Please input Product quantity that want to be adjust!'
                  
        if product_qty:
            if product_qty > can_process_qty:
                res['product_qty'] = can_process_qty
                warning_msgs = 'Current input quantity must not be greater than real can process quantity ' + str(can_process_qty)
            
        if warning_msgs:
            warning = {
                       'title': _('Invalid action !'),
                       'message' : warning_msgs
                    }
        return {'value': res, 'warning': warning}
    
  
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
